import Page from "@/components/page";
import PageNav from "@/components/pageNav";
import { View, Image } from "@tarojs/components";
import React, { useState } from "react";
import ArticleEdit from "./edit";
import ArticlePreview from "./preview";
import Taro from "@tarojs/taro";
import user from "@/store/user";
import { articleType } from "@/types";
import http from "@/request";
import { eventBus } from '@/event-bus';

import "./index.scss"

const ArticleDetail: React.FC = () => {
    const [pageMode, setPageMode] = useState<'edit' | 'read'>()
    const [article, setArticle] = useState<articleType>({})
    const [isPreview, setIsPreview] = useState<boolean>(false)

    Taro.useLoad((params) => {
        const { mode, id } = params
        setPageMode(mode || 'preview')
        if (id) {
            ArticleInfo(id)
        }
    })
    const onPreview = (res) => {
        setArticle(res)
        setIsPreview(true)
        setPageMode('read')
    }
    const onSuccess = (res) => {
        setArticle(res)
        setIsPreview(false)
        setPageMode('read')
        // 更新文章列表
        eventBus.emit('refreshArticleList');
    }
    const onBack = () => {
        setIsPreview(false)
        setPageMode('edit')
    }

    const ArticleInfo = (id) => {
        http.get('/article/detail', {
            id
        }).then(res => {
            const imgs = (res.data.imgs?.split(',') || []).filter(url => url)
            setArticle({
                ...res.data,
                imgs
            })
        })
    }

    return <Page className="article-detail-page font-size28 card-background text-main-color">
        <PageNav showBack className="article-detail-header">
            <View className="user-info flex-row flex-item">
                <Image className="user-avator" src={article?.avatarUrl || user.info?.avatarUrl || ''}></Image>
                <View className="user-name">{article?.userName || user.info?.userName || ''}</View>
            </View>
        </PageNav>
        <View className="page-body">
            {
                pageMode === 'edit' ?
                    <ArticleEdit
                        onPreview={onPreview}
                        onSuccess={onSuccess}
                        data={article}>
                    </ArticleEdit> :
                    <ArticlePreview
                        article={article}
                        isPreview={isPreview}
                        onBack={onBack}>
                    </ArticlePreview>
            }
        </View>
    </Page>
}

export default ArticleDetail